<template>
  <div class="userArticleList">
    <van-pull-refresh v-model="refreshLoading" @refresh="onRefresh" :success-text="successText">
      <van-list
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <article-item v-for="(atrtist,index) in list" :key="index" :article="atrtist"></article-item>
        <!-- <van-cell v-for="(atrtist,index) in list" :key="index" :title="atrtist.title" /> -->
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getUserArticles } from '@/api/user'
import articleItem from '@/components/article-item'
export default {
  components: {
    articleItem: articleItem
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      error: false, // 失败实例状态
      refreshLoading: false, // 下拉刷新状态
      successText: ''
    }
  },
  methods: {
    async onLoad() {
      try {
        const { data: res } = await getUserArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        // 模拟失败状态
        // if (Math.random() > 0.5) {
        //   JSON.parse('sfdfsd')
        // }
        console.log(res)
        this.list.push(...res.data.results)
        this.loading = false
        // 判断数据是否全部加载完成
        if (res.data.results.length) {
          this.timestamp = res.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (err) {
        // console.log(err)
        this.error = true
        this.loading = false
      }
    },
    async onRefresh() {
      try {
        const { data: res } = await getUserArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1
        })
        // 模拟失败状态
        // if (Math.random() > 0.2) {
        //   JSON.parse('sfdfsd')
        // }
        const { results } = res.data
        this.list.unshift(...results)
        this.refreshLoading = false
        this.successText = `更新了${results.length}条数据`
      } catch (err) {
        this.refreshLoading = false
        this.successText = '刷新失败,请重新尝试'
      }
    }
  }
}
</script>

<style lang='less' scoped>
.userArticleList {
  height: 79vh;
  overflow-y: auto;
}
</style>
